package com.sun.decrypt.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class MessageDigestUtils {
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    /**
     * 摘要算法
     * @param originalContent  加密原始串
     * @param algorithm         加密算法
     * @return
     */
    public static String doDigest(String originalContent,String algorithm){
        try {
            //获取摘要算法
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            byte[] digestBytes = digest.digest(originalContent.getBytes(UTF8));
            String hexStr = HexUtils.convertBytes2HexStr(digestBytes);
            return hexStr;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * mac算法
     * @param originalContent 加密原始串
     * @param key           密钥
     * @param algorithm     加密算法
     * @return
     */
    public static String doDigest(String originalContent,String key,String algorithm){
        try {
            //获取摘要算法
            Mac mac = Mac.getInstance(algorithm);
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(UTF8),algorithm);
            mac.init(keySpec);
            byte[] digestBytes = mac.doFinal(originalContent.getBytes(UTF8));
            String hexStr = HexUtils.convertBytes2HexStr(digestBytes);
            return hexStr;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
